﻿using OddUserManager.Data.IRepositories;
using OddUserManager.Model;
using System;
using System.Collections.Generic;
using System.Text;
using Dapper;
using System.Linq;

namespace OddUserManager.Data.Repositories
{
    public class AnalystSelectedMatchRepository : DapperBaseRepository<AnalystSelectedMatch, int>, IAnalystSelectedMatchRepository
    {
        public List<AnalystSelectedMatch> GetAnalystSelectedMatchsByMatchIdsAndUserId(List<int> ids,int userId)
        {
            List<AnalystSelectedMatch> list = null;
            var idsString = string.Join(",", ids);
            using (var con = GetOpenConnection())
            {
                var sql = $"select * from AnalystSelectedMatch where CreateAppUserId={userId} and MatchId in({idsString});" +
                    $"select * from AnalystDetailSelectedContents where AnalystSelectedMatch in(select Id from AnalystSelectedMatch where  CreateAppUserId={userId} and MatchId in({idsString}))";
                list = con.QueryMultiple(sql, null, null, 3000, null).Map<AnalystSelectedMatch, AnalystDetailSelectedContents, int>
                      (
                      m => m.Id,
                      c => c.AnalystSelectedMatch,
                      (m, cs) => { m.DetailSelectedContentsList = cs.ToList(); }
                      ).ToList();
            }
            return list;
        }
        public List<AnalystSelectedMatch> GetAnalystSelectedMatchsByMatchIds(List<int> ids)
        {
            List<AnalystSelectedMatch> list = null;
            var idsString = string.Join(",", ids);
            using (var con = GetOpenConnection())
            {
                var sql = $"select * from AnalystSelectedMatch where MatchId in({idsString});" +
                    $"select * from AnalystDetailSelectedContents where AnalystSelectedMatch in(select Id from AnalystSelectedMatch where  MatchId in({idsString}))";
                list = con.QueryMultiple(sql, null, null, 3000, null).Map<AnalystSelectedMatch, AnalystDetailSelectedContents, int>
                      (
                      m => m.Id,
                      c => c.AnalystSelectedMatch,
                      (m, cs) => { m.DetailSelectedContentsList = cs.ToList(); }
                      ).ToList();
            }
            return list;
        }
        public bool InsertOrUpdate(AnalystSelectedMatch entity)
        {
            bool isSuccess = false;
            var model = GetAnalystSelectedMatchByMatchIdAndAppUserId(entity.MatchId, entity.CreateAppUserId);

            using (var con = GetOpenConnection())
            {
                var trans = con.BeginTransaction();
                try
                {
                    if (null == model)
                    {
                        var sql = $"INSERT INTO [dbo].[AnalystSelectedMatch] ([MatchId] ,[CreateAppUserId] ,[CreateTime],[LastUpdateTime],[BookMarksString],[Remark],[SP],[ResultChance],[Issue],[WeekName]) VALUES ({entity.MatchId},{entity.CreateAppUserId},'{entity.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")}','{entity.LastUpdateTime.ToString("yyyy-MM-dd HH:mm:ss")}','{entity.BookMarksString}','{entity.Remark}',{entity.SP},{entity.ResultChance},'{entity.Issue}','{entity.WeekName}');select SCOPE_IDENTITY()";
                        var id = con.Query<int>(sql,null,trans,true,3000,null).FirstOrDefault();

                        entity.DetailSelectedContentsList.ForEach(p =>
                        {
                            var childSql =$"insert into AnalystDetailSelectedContents([WeekName],[AnalystSelectedMatch],[SelectedMatchId],[SelectedResult],[FixOdds],[SelectedOdds],[SelectedPayReturn],[GoodLevel],[SelectedChance]) VALUES('{p.WeekName}',{id},{p.SelectedMatchId},{((int)p.SelectedResult)},'{p.FixOdds}',{p.SelectedOdds},{p.SelectedPayReturn},{p.GoodLevel},{p.SelectedChance})";
                            con.Execute(childSql, null, trans, 3000, null);
                        });

                    }
                    else
                    {
                        var sql = $"update AnalystSelectedMatch set LastUpdateTime='{entity.LastUpdateTime.ToLongTimeString()}',BookMarksString='{entity.BookMarksString}',Remark='{entity.Remark}',SP={entity.SP},ResultChance={entity.ResultChance} where Id={model.Id}";
                        con.Execute(sql, null, trans, 3000, null);
                        var deleteSql = $"delete from AnalystDetailSelectedContents where AnalystSelectedMatch={model.Id}";
                        con.Execute(deleteSql, null, trans, 3000, null);

                        entity.DetailSelectedContentsList.ForEach(p =>
                        {
                            var childSql = $"insert into AnalystDetailSelectedContents([WeekName],[AnalystSelectedMatch],[SelectedMatchId],[SelectedResult],[FixOdds],[SelectedOdds],[SelectedPayReturn],[GoodLevel],[SelectedChance]) VALUES('{p.WeekName}',{model.Id},{p.SelectedMatchId},{(int)p.SelectedResult},'{p.FixOdds}',{p.SelectedOdds},{p.SelectedPayReturn},{p.GoodLevel},{p.SelectedChance})";
                            con.Execute(childSql, null, trans, 3000, null);
                        });
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
            }
               

            return isSuccess;
        }

        private AnalystSelectedMatch GetAnalystSelectedMatchByMatchIdAndAppUserId(int matchId, int appUserId) {
            AnalystSelectedMatch model = null;
            using (var con = GetOpenConnection())
            {
                var sql = $"select * from AnalystSelectedMatch where MatchId={matchId} and CreateAppUserId={appUserId}";
                model = con.Query<AnalystSelectedMatch>(sql, null, null, true, 3000, null).FirstOrDefault();
            }
            return model;
        }


        public IEnumerable<AnalystSelectedMatch> LoadPageList(int startPage, int pageSize, out int rowCount, Func<AnalystSelectedMatch, bool> where, Func<AnalystSelectedMatch, object> order)
        {
            throw new NotImplementedException();
        }

        public List<AnalystSelectedMatch> GetAnalystSelectedMatchsByAppUserId(int userId)
        {
            throw new NotImplementedException();
        }

        public new void  Delete(int id) {
            using (var con = GetOpenConnection())
            {
                var sql = $"delete from AnalystDetailSelectedContents where AnalystSelectedMatch={id};delete from AnalystSelectedMatch where Id={id}";
                con.Execute(sql);
            }
        }

        
    }
}
